package tcp2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket = new ServerSocket(8888);
		
		while(true){
			Socket socket = serverSocket.accept();
			InputStream in = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			out.write("Pls input the file name:\n".getBytes());
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			String name = reader.readLine();
			
			File file = new File("ftp/"+name);
//			if (!file.exists()) {
//				out.write("couldn't find the file!".getBytes());
//			}else {
//				out.write("transfer begin...".getBytes());
//				BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(file));
//				while(fileIn.read()!=-1){
//					out.write(fileIn.read());
//				}
//				fileIn.close();
//				out.write("finished!".getBytes());
//			}
			
			while(!file.exists()){
				out.write("couldn't find the file! input again:\n".getBytes());
				file = new File("ftp/"+reader.readLine());
			}
			
			out.write("OK\n".getBytes());
			
//			BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(file));
//			int i = fileIn.read();
//			while(i!=-1){
//				out.write(i);
//				i=fileIn.read();
//			}
//			fileIn.close();
			
			InputStream fin=new FileInputStream(file);
			byte[] buf=new byte[fin.available()];
			fin.read(buf);
			out.write(buf);
			fin.close();
			
			reader.close();
			in.close();
			out.close();
			socket.close();
		}
		
	}

}
